/*
 * Arquivo.cpp
 *
 *  Created on: 08/10/2009
 *      Author: hfluz
 */

#include "Arquivo.h"
#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

Arquivo::Arquivo ()
{
}

Arquivo::Arquivo (char* nome, char* mode)
{
    this->arq = fopen (nome, mode);
    if (arq != NULL)
        fseek(this->arq, 0, 0);
    linha_atual = 1;admrede
}

bool Arquivo::haveCaracters ()
{
    return !feof(this->arq);
}

char Arquivo::readCaracter()
{
    char caracter;
    fscanf(arq, "%c", &caracter);
    return caracter;
}

void Arquivo::writeString (string texto)
{
    int tamanho = texto.size() + 1;
    char* token = new char[tamanho];
    strcpy (token, texto.c_str());
    fprintf (this->arq, "%s", token);
}

void Arquivo::writeNumber(int num)
{
    fprintf (this->arq, "%d", num);
}
void Arquivo::mudarPonteiro (int delta, int pos)
{
    if (this->haveCaracters())
        fseek (this->arq, delta, pos);
}

void Arquivo::getPalavra (char* string)
{
      char read = this->readCaracter();
      int i = 0;

      while (read == ' ' || read == ':' || read == '\n' || read == '\t') { //numero

        read = this->readCaracter();
      }

      while (read != '\n' && this->haveCaracters() && read != ' ' && read != ':' && read != '\t') {
            if (read >= 97 && read <= 122)
                read -= 32;
            string[i] = read;
            i++;
            read = this->readCaracter();
      }
      string[i] = 0;

      while ((read == '\n' || read == ' ' || read == ':'|| read == '\t') && !this->FimArq()) {

          read = this->readCaracter();
      }

      if (!this->FimArq())
          this->mudarPonteiro(-1, 1);
}

int Arquivo::getNumero ()
{
    char read = this->readCaracter();
    int num = 0;
    bool negativo = false;
    while (read == '\n' || read == ' ' || read == '\t' || read == ',')
    {
        read = this->readCaracter();
    }
    if (read == '-') {

         negativo = true;
         read = this->readCaracter();
    }
    while (read != '\n' && this->haveCaracters() && read != ' ' && read != ',' && read != '\t') {
         num = 10*num + (read-48);
         read = this->readCaracter();
    }

    if (negativo) {
        num = num * (-1);
    }

    while ((read == '\n' || read == ' ' || read == '\t' || read == ',') && !this->FimArq())
    {
        read = this->readCaracter();
    }

    if (!this->FimArq())
        this->mudarPonteiro(-1,1);

    return  num;
}

bool Arquivo::FimArq()
{
    return feof(this->arq);
}
